<?php
require_once(R_P . 'require/class_file.php');

class Resource extends File
{
	/**
	 * 获取资源的查询条件
	 *
	 * @var string
	 */
	protected $sqlAdd;
	protected $wmpExt = array('avi','wmv');
	protected $rmExt = array('rm','rmvb');
	protected $files_img = 'images/admin/file/';

	/**
	 * 服务器信息
	 *
	 * @var array
	 */
	//protected $server = array();

	/**
	 * 在前台访问时，按照授权目录才能浏览
	 *
	 * @var array
	 */
	protected $cate_allow = null;

	public function __construct()
	{
		parent::__construct();
		global $cate;
		if (!function_exists('adminmsg')) //仅仅前台需要
		{
			$cate_allow = $cate->getAllow();
			if (!empty($cate_allow)) {
				$cids = implode(',', $cate_allow);
				$this->sqlAdd[] = 'r.cid IN(' . $cids . ')';
			}
			else
			{
				$this->sqlAdd[] = 'r.cid=-1'; //没有任何权限浏览
			}
		}
	}

	/**
	 * 上传资源
	 *
	 */
	public function upload($resTitle = '', $tid = '', $cid = '')
	{
		global $timestamp, $db, $very, $catedb;

		$forbidden_ext = array('php','htm','html');
		//禁止上传这些文件
		$videoSQL = ''; //视频所需要的SQL语句
		$i = 0;
		$uploadNum = 0;
		$rids = array();
		foreach ($_FILES as $key=>$value)
		{
			$i++;
			if(is_array($value))
			{
				$filename = $value['name'];
				$tmpfile = $value['tmp_name'];
				$filesize = $value['size'];
			}
			else
			{
				$filename = ${$key.'_name'};
				$tmpfile = $$key;
				$filesize = ${$key.'_size'};
			}

			if(!$this->if_uploaded_file($tmpfile))	continue;

			$file_ext = end(explode('.',$filename));
			$file_ext = strtolower($file_ext);
			in_array($file_ext, $forbidden_ext) && exit('pub_uploadext');

			/* 该目录没有单独设置存储路径则采用系统默认存储点 */
			$serverid = empty($catedb[$cid]['serverid']) ? $very['serverid'] : $catedb[$cid]['serverid'];

			//获取该资源所应该存储的位置
			if (!isset($this->server[$serverid])) {
				Showmsg('该目录的存储节点已经被删除或者尚未设置有效的存储节点');
			}
			$serverpath = $this->server[$serverid]['serverpath']; //根路径
			$filedir = $this->saveDir($serverpath);  //其相对根路径的相对路径
			$savedir = $serverpath . '/' . $filedir; //绝对路径

			$randvar = uniqid($uploadNum); //随机文件名
			$upfilename = $randvar . '.' . $file_ext;

			$filepath = $filedir . '/' . $upfilename;		//用于存储到数据库中的相对路径
			$target = $savedir . '/' . $upfilename;			//用于操作文件的绝对路径
			$target = strtolower($target);

			if(!$this->postupload($tmpfile, $target))
			{
				Showmsg('pub_uploadfail');
			}
			if (in_array($file_ext, $this->imgExt)) //图片文件
			{
				$upfilename_s1 = $randvar.'_s1.' . $file_ext;	//随机文件名，缩略1
				$upfilename_s2 = $randvar.'_s2.' . $file_ext;	//随机文件名，缩略2
				$this->resize_image($target, $savedir . '/' . $upfilename_s1, 100,100);
				$this->resize_image($target, $savedir . '/' . $upfilename_s2, 500,500);
			}
			elseif (in_array($file_ext, $this->videoExt))
			{
				//视频格式，标志其是一个视频，然后等待转码队列调度
				$videoSQL = ',ifvideo=1';
				//$videoinfo = $this->videoScreen($target);
				//$frameimg = $videoinfo  ? 1 : 0;
				//$videoinfo = addslashes(serialize($videoinfo)); //准备入库
			}
			//$title = empty($resTitle[$i]) ? substr($filename, 0 , -(strlen($file_ext) + 1)) : Char_cv($resTitle[$i]);
			$title = Char_cv($resTitle[$i]);

			$db->update("INSERT INTO cms_resource SET
				tid='$tid',
				type='$file_ext',
				filetitle='$title',
				filename='$filename',
				filepath='$filepath',
				size='$filesize',
				uploadtime='$timestamp',
				serverid='$serverid',
				cid='$cid'
				$videoSQL
			");
			$rids[] = $db->insert_id();
			$uploadNum++;
			/*
			$this->fileName = $filename;
			$this->filePath = $filepath;
			*/
		}
		return $rids;
	}

	/**
	 * 给文件改名
	 *
	 * @param array $arr
	 */
	public function rename($arr)
	{
		global $db;
		foreach ($arr as $rid => $filetitle)
		{
			if (empty($filetitle)) continue; //空的不处理
			$rid = intval($rid);
			$filetitle = Char_cv($filetitle);
			$db->update("UPDATE cms_resource SET filetitle='$filetitle' WHERE rid='$rid'");
		}
	}

	/**
	 * 获得文件
	 *
	 * @param unknown_type $tid
	 * @return unknown
	 */
	public function get($tid = '')
	{
		return $this->getOne($tid);
	}

	/**
	 * 返回内容总数
	 *
	 * @param integer $tid
	 * @return integer
	 */
	public function countOne($tid)
	{
		global $db;
		$rs = $db->get_one("SELECT COUNT(*) AS total FROM cms_resource WHERE tid = '$tid' AND delflag = 0");
		return $rs['total'];
	}

	/**
	 * 返回单个内容下的所有文件
	 *
	 * @param integer $tid
	 * @return array
	 */
	public function getOne($tid = '', $rid = 0, $page = null)
	{
		global $db, $very;
		if (!empty($rid))
		{
			$rid = intval($rid);
			$sqlAdd = " AND rid = '$rid'";
		}
		if (!is_null($page)) {
			$page <= 1 && $page = 1;
			$pagesize = !$very['content_pagesize'] ? 25 : $very['content_pagesize'];
			$start = ($page -1)*$pagesize;
			$sqlAdd = " LIMIT $start, $pagesize";
			//echo $sqlAdd;exit;
		}
		$rs = $db->query("SELECT * FROM cms_resource WHERE tid = '$tid' AND delflag = 0 $sqlAdd");
		$resource = array();
		while ($res = $db->fetch_array($rs))
		{
			empty($res['filetitle']) && $res['filetitle'] = $res['filename'];
			$res['icon'] = $this->getIcon($res['type']);

			if (function_exists('adminmsg')) //后台的预览url
			{
				$res['previewurl'] = $this->getPreviewUrl($res['type'], $res['filepath']);
			}
			else
			{
				$res['url'] = $this->server[$res['serverid']]['serverurl'] . $res['filepath'];
				/* 前台 */
				if (in_array($res['type'], $this->imgExt))
				{
					$previewurl = $this->getSmallPic($res['filepath']);
					
					$res['preview'] = '<a href="file.php?tid=' . "$res[tid]&cid=$res[cid]&rid=$res[rid]" . '"><img src="images/icon/image.png" align="absmiddle" title="预览" /></a>';
					$res['picurl'] = $this->server[$res['serverid']]['serverurl'] . $previewurl[1];

					//print_r($res);
					/* 只在*/
					if (!empty($rid))
					{
						$res['fileexif'] = $this->getFileExif($this->server[$res['serverid']]['serverpath'] . '/' . $res['filepath']);
					}
					$res['showpic'] = 1; //图片类型
				}
				elseif ($res['ifconvert'] && in_array($res['type'], $this->videoExt))
				{
					//$res['url'] = $this->server[$res['serverid']]['serverurl'] . $res['filepath'];
					$res['videopic'] = $this->getFramePic($res['url'], 3);
					$res['flvurl'] = $this->getFlv($res['url']);
					$res['preview'] = '<a href="file.php?tid=' . "$res[tid]&cid=$res[cid]&rid=$res[rid]" . '"><img src="images/icon/film_go.png" align="absmiddle" title="预览此视频" /></a>';
					if (!empty($rid))
					{
						$res['fileexif'][2] = $this->getVideoInfo(unserialize($res['videoinfo']));
					}
					$res['showpic'] = 2; //视频类型
				}
			}

			$res['filesize'] = $this->getFileSize($res['size']);
			$res['uploadtime'] = get_date($res['uploadtime'],'y-m-d H:i');
			$resource[] = $res;
		}
		return $resource;
	}

	/**
	 * 设置查询类别
	 *
	 * @param string $type
	 */
	public function setType($type = '')
	{
		if ($type == 'other')
		{
			$extArray = $extString = array();
			foreach ($GLOBALS['restype'] as $res)
			{
				$extArray = array_merge($extArray, $res['typeext']);
			}
			foreach ($extArray as $newExt)
			{
				$extString[] = "'$newExt'"; //加引号操作
			}

			$this->sqlAdd[] = ' r.type NOT IN(' . implode(',', $extString) . ')';
		}
		elseif (!empty($type) && $type != 'all')
		{
			$ext = $GLOBALS['restype'][$type]['typeext'];
			//$ext = $this->exttype[$type];
			//$extArr = explode(',', $ext);
			$extString = array();
			foreach ($ext as $newExt)
			{
				$extString[] = "'$newExt'"; //加引号操作
			}

			$this->sqlAdd[] = ' r.type IN(' . implode(',', $extString) . ')';
		}
	}

	/**
	 * 设置查询条件
	 *
	 * @param unknown_type $env
	 */
	public function setWhere($env)
	{
		$this->sqlAdd[] = $env;
	}

	/**
	 * 查询条件
	 *
	 * @return unknown
	 */
	public function getWhere()
	{
		if (empty($this->sqlAdd))
		{
			return '';
		}
		else
		{
			return ' WHERE ' . implode(' AND ', $this->sqlAdd);
		}
	}

	/**
	 * 获取数量
	 *
	 * @return integer
	 */
	public function getListNum($limitNum = 0)
	{
		global $db;

		$sqlAdd = $this->getWhere();
		$sql = "SELECT COUNT(*) AS total FROM cms_resource r LEFT JOIN cms_contentindex c USING(tid) $sqlAdd ";
		//echo $sql;		
		$rs = $db->get_one($sql);
		if ($limitNum > 0 && $rs['total'] > $limitNum)
		{
			return $limitNum;
		}
		else 
		{
			return $rs['total'];
		}
	}

	/**
	 * 获取一些资源列表
	 *
	 * @param integer $page
	 * @param integer $pageSize
	 * @return array
	 */
	public function getList($page = 1, $pageSize = 20, $orderby = 'rid')
	{
		global $db;
		$sqlAdd = $this->getWhere();
		$page < 1 && $page = 1;
		$start = ($page - 1)*$pageSize;
		empty($orderby) && $orderby = 'uploadtime';
		$rs = $db->query("SELECT * FROM cms_resource r LEFT JOIN cms_contentindex c USING(tid) $sqlAdd ORDER BY r.$orderby DESC LIMIT $start, $pageSize");
/*		echo "SELECT * FROM cms_resource r LEFT JOIN cms_contentindex c USING(tid) $sqlAdd ORDER BY r.$orderby DESC LIMIT $start, $pageSize";
		var_dump($rs);
		exit;*/
		$resource = array();
		while ($res = $db->fetch_array($rs))
		{
			empty($res['filetitle']) && $res['filetitle'] = $res['filename'];
			$res['icon'] = $this->getIcon($res['type']);
			$res['server'] = $this->server[$res['serverid']]['servername'];
			
			/*获取图片尺寸*/
			$path = $this->server[$res['serverid']]['serverpath'] . $res['filepath'];
			if (in_array($res['type'], $this->imgExt)) {
				$path = $this->getSmallPic($path);
				$path = $path[1];
				list($res['picwidth'], $res['picheight']) = getimagesize($path);
				//echo "$res[picwidth], $res[picheight] <BR>";
			}
			elseif ($res['ifconvert'])
			{
				//$path = $this->getFramePic($path, 1);
				//list($res['picwidth'], $res['picheight']) = getimagesize($path);
				//echo "$res[picwidth], $res[picheight] <BR>";
			}
			$res['url'] = $this->server[$res['serverid']]['serverurl'] . $res['filepath'];
			$res['flvurl'] = $this->getFlv($res['url']);
			$res['filesize'] = $this->getFileSize($res['size']);
			$res['uploadtime'] = get_date($res['uploadtime'],'y-m-d H:i');
			if ($res['ifconvert']) {
				$res['videopic'] = $this->getFramePic($res['url'], 2);
				//$res['videopic_1'] = $this->getFramePic($res['url'], 1);
			}

			if (function_exists('adminmsg')) {
				$res['previewurl'] = $this->getPreviewUrl($res['type'], $res['url']);
			}
			$resource[] = $res;
		}
		return $resource;
	}

	/**
	 * 获取文件小图标
	 *
	 * @param string $type
	 * @return string
	 */
	public function getIcon($type)
	{
		global $fileicon;

		if (strpos($type, '.')) $type = end(explode('.', $type));

		$type = strtolower($type);
		if(in_array($type, $fileicon))
		{
			return 'images/admin/file/' . $type . '.gif';
		}
		else
		{
			return 'images/admin/file/default.gif';
		}

	}

	/**
	 * 删除一个资源
	 *
	 * @param integer $rid
	 * @return unknown
	 */
	public function remove($rid, $tid)
	{
		global $db;
		$tid = intval($tid);
		
		$this->delete($rid); //删除物理文件
		if (is_array($rid))
		{
			$rids = implode(',', $rid);
			$db->query("DELETE FROM cms_resource WHERE rid IN($rids) AND tid='$tid'");
		}
		else
		{
			$db->query("DELETE FROM cms_resource WHERE rid ='$rid' AND tid='$tid'");
		}

		$resNum = $db->affected_rows(); //准确的判断被删除的行数
		$db->query("UPDATE cms_contentindex SET resnum=resnum - $resNum WHERE tid='$tid'");
		return $resNum;
	}

	/**
	 * 获取下一个内容下的文件
	 *
	 * @param unknown_type $tid
	 * @param unknown_type $rid
	 * @return unknown
	 */
	public function getNextOne($tid, $rid)
	{
		global $db;
		$rs = $db->get_one("SELECT rid,cid,tid,filetitle,filename FROM cms_resource WHERE rid>$rid AND tid=$tid AND delflag=0  ORDER BY rid ASC LIMIT 1");
		empty($rs['filetitle']) && $rs['filetitle'] = $rs['filename'];
		return $rs;
	}

	public function getPreOne($tid, $rid)
	{
		global $db;
		$rs = $db->get_one("SELECT rid,cid,tid,filetitle,filename FROM cms_resource WHERE rid<$rid AND tid=$tid AND delflag=0  ORDER BY rid DESC LIMIT 1");
		empty($rs['filetitle']) && $rs['filetitle'] = $rs['filename'];
		return $rs;
	}
}
?>